package com.base.service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;
import org.hibernate.type.StringType;
import org.hibernate.type.Type;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import tool.ClientTool;
import tool.JsonTool;
import tool.TimeTool;

import com.base.bean.*;
import com.base.dao.*;
import com.base.domain.*;
import com.hf.bean.ActivityCount;


/**
 * 行动服务类
 * 
 * @author Administrator
 * 
 */

public class ActivityService {

	// 单例模式 start
	private volatile static ActivityService instance = null;
	
	private ActivityDao actvtDao;
	
	static String[] actvType = {"", "空白市场开发", "二级渠道开发", "新客户拜访", "老客户拜访", "商务谈判", "交机", "备注其他", "客户催款","电话拜访"};
	
	
	
	private ActivityService() {
		actvtDao = (ActivityDao) _BaseDao.ac.getBean("ActivityDao");
		

	}
	public static ActivityService getInstance() {
		if (instance == null) {
			synchronized (ActivityService.class) {// 1
				if (instance == null) {// 2
					instance = new ActivityService();// 3
				}
			}
		}
		return instance;
	}
	// 单例模式 end

	public ActvtDetail getByAid(Integer aid){
		ActvtDetail actvDetail=new ActvtDetail();
		try{
		actvDetail.setActivity(actvtDao.findByHql("from Activity a where a.aid="+aid).get(0));
		
		return actvDetail;
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 当月有效行动数
	 * @return
	 */
	
	/*
	
	public int getTotal(Integer owner,Integer state){
		Session session = null;
		int count=0;
	try{	
		session = ClientService.getInstance().getClientBaseDao()
				.getSessionFactory().getCurrentSession();
		Criteria criteria = null;
		Transaction tx = null;

		// try begin
		tx = session.beginTransaction();
		criteria = session.createCriteria(ClientBase.class);
		criteria.add(Restrictions.eq("owner", owner)); // 属于自己的
		criteria.add(Restrictions.eq("state", state)); // state=1 有效状态
		criteria.setProjection(Projections.rowCount());
		count=Integer.parseInt(criteria.uniqueResult().toString());
		tx.commit();
		return count;
	}catch(Exception e){
		e.printStackTrace();
		return 0;
	}finally{
		if (session.isOpen())
			session.close();
	}
	}
	
	*/
	
	
	public List<ActivityCount> getCurrentMonthCountByType(Integer uid){
		
		List<ActivityCount> acList = new ArrayList<ActivityCount>();
		
		Timestamp start = TimeTool.getMonthStartOrEnd(1);
		Timestamp end = TimeTool.getMonthStartOrEnd(2);
		Session session = null;
		int count=0;
		
		session = ActivityService.getInstance().getActvtDao()
				.getSessionFactory().getCurrentSession();
		
		Criteria criteria = null;
		Transaction tx = null;
		List list = null; 

		// try begin
		tx = session.beginTransaction();
		criteria = session.createCriteria(Activity.class);
		criteria.add(Restrictions.eq("creator", uid));
		criteria.add(Restrictions.eq("checked", 1));
		criteria.add(Restrictions.ge("created", start));
		criteria.add(Restrictions.le("created", end));
		
		ProjectionList projList = Projections.projectionList();
		// projList.add(Projections.sum("aid"));  
		projList.add(Projections.groupProperty("type")); 
		projList.add(Projections.count("aid")); 
		criteria.setProjection(projList);  
		list = criteria.list(); 
		list = list == null ? new ArrayList() : list;  
		
		
		Iterator iter = list.iterator();  
		  if (!iter.hasNext()) {  
		   System.out.println("No objects to display.");  
		  
		  }  
		  while (iter.hasNext()) {  
//		   System.out.println("New object");  
		   ActivityCount data = new ActivityCount();
		   Object[] obj = (Object[]) iter.next();  
		   for (int i = 0; i < obj.length; i++) {
			   data.setActvtType(new Integer(obj[0].toString()));
			   data.setActvtTypeName(this.actvType[new Integer(obj[0].toString())]);
			   data.setCount(new Integer(obj[1].toString()));
		   }
		   acList.add(data);
		  }
		
		return acList;
		
	}
	
	public int getCurrentMonthCount(Integer uid){
		Timestamp start = TimeTool.getMonthStartOrEnd(1);
		Timestamp end = TimeTool.getMonthStartOrEnd(2);
		Session session = null;
		int count=0;
		try{
		session = ActivityService.getInstance().getActvtDao()
				.getSessionFactory().getCurrentSession();
		
		Criteria criteria = null;
		Transaction tx = null;

		// try begin
		tx = session.beginTransaction();
		criteria = session.createCriteria(Activity.class);
		criteria.add(Restrictions.eq("creator", uid));
		criteria.add(Restrictions.eq("checked", 1));
		criteria.add(Restrictions.ne("type", 9));
		criteria.add(Restrictions.ge("created", start)); // 属于自己的
		criteria.add(Restrictions.le("created", end)); // state=1 有效状态
		criteria.setProjection(Projections.rowCount());
		count=Integer.parseInt(criteria.uniqueResult().toString());
		tx.commit();
		return count;
		}catch(Exception e){
			e.printStackTrace();
			return 0;
		}finally{
			if (session.isOpen())
				session.close();
		}
	}
	
	
	
	
	
	/**提交行动(数据库保存了image的所有信息  但是image当时并未下载下来 )
	 * @see activity:creator cid longitude latitude address不能为空
	 */
	public Activity creatActvt(Integer creator,String mediaId,String longitude,String latitude){
	try{	
//		Image image=ImageService.getInstance().upload(actvt.getCreator(), mediaId, longitude, latitude);
		Image image=ImageService.getInstance().saveImageInfo(creator, mediaId, longitude, latitude,2);
		
		Activity actvt=new Activity();
		actvt.setPath(image.getPath());
		actvt.setCreated(image.getCreated());
		actvt.setPhotoName(image.getFileName());
		actvt.setState(image.getState());	//3:重复  0：未审核
		if(image.getState()!=3){
			actvtDao.merge(actvt);
		}
		return actvt;
	}catch(Exception e){
		e.printStackTrace();
		return null;
	}
	}
	
	
	
	public static void main(String[] args){
		ActivityService as = ActivityService.getInstance();
		int count = as.getCurrentMonthCount(75);
		System.out.println(count);
		System.out.println("---------------------");
		List<ActivityCount> list = as.getCurrentMonthCountByType(75);
		for(ActivityCount a:list){
				System.out.println(a.getActvtTypeName()+"--"+a.getCount());
		}
	}
	
	public ActivityDao getActvtDao() {
		return actvtDao;
	}
	
	
	
	

}
